<template>
  <div class="lcds-root-container">
    <div class="lc-form" style="--formItemSpace: 200px">
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        :disabled="status === 'preview'"
        label-width="150px"
      >
        <lc-rower>
          <el-form-item class="lc-form-item" label="订单编码" prop="orderCode">
            <div class="lc-form-item__box">
              <el-input
                class="lc-input"
                v-model="formModel.orderCode"
                placeholder="请输入"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="lc-form-item" label="订单名称" prop="orderName">
            <div class="lc-form-item__box">
              <el-input
                class="lc-input"
                v-model="formModel.orderName"
                placeholder="请输入"
              >
              </el-input>
            </div>
          </el-form-item>
        </lc-rower>
        <lc-rower>
          <el-form-item
            class="lc-form-item"
            label="订单金额"
            prop="orderAmount"
          >
            <div class="lc-form-item__box">
              <el-input-number
                class="lc-input-number"
                v-model="formModel.orderAmount"
                :controls="true"
                placeholder="请输入"
              ></el-input-number>
            </div>
          </el-form-item>
          <el-form-item
            class="lc-form-item"
            label="订单商品数量"
            prop="orderGoodsCount"
          >
            <div class="lc-form-item__box">
              <el-input-number
                class="lc-input-number"
                v-model="formModel.orderGoodsCount"
                :controls="true"
                placeholder="请输入"
              ></el-input-number>
            </div>
          </el-form-item>
        </lc-rower>
        <lc-rower>
          <el-form-item
            class="lc-form-item"
            label="订单明细表列表"
            prop="myOrderItemDtoList"
          >
            <div class="lc-form-item__box">
              <lc-editor-table
                ref="myOrderItemDtoListRef"
                :data.sync="formModel.myOrderItemDtoList"
                :columns="myOrderItemDtoListColumns"
                input-width="120px"
                :topAddBtnAble="true"
                :rowOperates="['add', 'edit', 'delete']"
                style="--form-input-width: 120px"
              >
                <template #goodsCode="scope">
                  <el-input
                    class="lc-input"
                    v-model="scope.row.goodsCode"
                    placeholder="请输入"
                  >
                  </el-input>
                </template>

                <template #goodsName="scope">
                  <el-input
                    class="lc-input"
                    v-model="scope.row.goodsName"
                    placeholder="请输入"
                  >
                  </el-input>
                </template>

                <template #goodsCount="scope">
                  <el-input-number
                    class="lc-input-number"
                    v-model="scope.row.goodsCount"
                    :controls="true"
                    placeholder="请输入"
                  ></el-input-number>
                </template>

                <template #goodsPrice="scope">
                  <el-input-number
                    class="lc-input-number"
                    v-model="scope.row.goodsPrice"
                    :controls="true"
                    placeholder="请输入"
                  ></el-input-number>
                </template>

                <template #goodsAmount="scope">
                  <el-input-number
                    class="lc-input-number"
                    v-model="scope.row.goodsAmount"
                    :controls="true"
                    placeholder="请输入"
                  ></el-input-number>
                </template>
              </lc-editor-table>
            </div>
          </el-form-item>
        </lc-rower>
        <div
          v-if="btnGroupVisible"
          class="lc-buttonGroup lc-buttonGroup__level"
          style="justify-content: center"
        >
          <el-button class="lc-button" size="large" @click="resetForm">
            取消
          </el-button>
          <el-button
            class="lc-button"
            size="large"
            type="primary"
            @click="submitForm"
          >
            保存
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, unref, onBeforeMount } from "vue";
import { request } from "@/apis/request";
import { ElMessage } from "element-plus";
defineOptions({
  name: "OrderForm",
});

const emit = defineEmits(["submit"]);

const props = defineProps({
  btnGroupVisible: { type: Boolean, default: true },
  status: { type: String, default: "" },
  id: { type: String, default: "" },
});

const formModel = ref({
  orderCode: "",
  orderName: "",
  orderAmount: "",
  orderGoodsCount: "",
  myOrderItemDtoList: [],
});
const myOrderItemDtoListColumns = ref([
  { prop: "goodsCode", label: "商品编号" },
  { prop: "goodsName", label: "商品名称" },
  { prop: "goodsCount", label: "商品数量" },
  { prop: "goodsPrice", label: "商品单价" },
  { prop: "goodsAmount", label: "商品总价" },
]);
const myOrderItemDtoListData = ref([]);
const myOrderItemDtoListRef = ref(null);
const formRef = ref(null);
const loading = ref(false);
const rules = ref({});
const searches = new URLSearchParams(document.location.search.substring(1));
const formStatus = props.status || searches.get("status") || "add";

const resetForm = () => {
  unref(formRef).resetFields();
};
const submitForm = async () => {
  const validated = await unref(formRef).validate();
  if (validated) {
    let params;
    if (formStatus === "add") {
      params = {
        url: "/v1/gateway/1648160260487245826/1767862025555623940",
        method: "POST",
        headers: { token: "${x-user-token}" },
        responseType: "APPLICATION/JSON",
        data: { ...formModel.value },
      };
    } else if (formStatus === "edit") {
      params = {
        url: "/v1/gateway/1648160260487245826/1767862025555623941",
        method: "PUT",
        headers: { token: "${x-user-token}" },
        responseType: "APPLICATION/JSON",
        data: { ...formModel.value },
      };
    }
    loading.value = true;
    request(params)
      .then((res = {}) => {
        if (res.success) {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          emit("submit", "success");
          return "success";
        } else {
          ElMessage({
            message: res.message,
            type: "error",
          });
          emit("submit", "failed");
          return "failed";
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
};
const queryFormData = (queryData = {}) => {
  let params = {
    url: "/v1/gateway/1648160260487245826/1767862025555623936",
    method: "GET",
    headers: { token: "${x-user-token}" },
    responseType: "APPLICATION/JSON",
  };
  loading.value = true;
  return request({
    ...params,
    params: {
      ...queryData,
    },
  })
    .then((res = {}) => {
      const data = res.data || {};
      Object.keys(data).forEach((key) => {
        formModel.value[key] = [null, undefined].includes(data[key])
          ? formModel.value[key]
          : data[key];
      });
    })
    .finally(() => {
      loading.value = false;
    });
};

onBeforeMount(() => {
  if (["edit", "preview"].includes(formStatus)) {
    const primaryKeyVal = props.id || searches.get("id ");
    formModel.value.id = primaryKeyVal;
    queryFormData({
      id: primaryKeyVal,
    });
  }
});

defineExpose({
  resetForm,
  submitForm,
});
</script>
